// --------------------------------------------------------------------
//   name 	: 
//   desc 	: 
//   version 	: 
//   dev 	: 
// --------------------------------------------------------------------
// DEPENDENCIES
// 
// --------------------------------------------------------------------
// CHANGE HISTORY
// 0.1 	Initial Release
// --------------------------------------------------------------------
	plugins.mapexpand = { // Expand the map to be X times it's regular size
	// Map Points Tracking
		'get_mpt_xhtml' : function(village_coords, points){
			if(TW_Mpt[village_coords] == null) return "";

			plugins.mapexpand.put_mpt(village_coords, points);
			var delta = points - TW_Mpt[village_coords];
			if(delta > 0) return ' <span style="color:green">(+' + delta + ')</span>';
			if(delta == 0) return ' <span style="color:black">(0)</span>';
			return ' <span style="color:red">(-' + Math.abs(delta) + ')</span>';
		},


// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
  'get_mpt' : function (){
	  var cacheMpt = getValue("MPTrk");
	  if(!cacheMpt || cacheMpt == ""){
		  cacheMpt = [];
	  }else{
		  cacheMpt = unserialize(cacheMpt);
	  }
	  return cacheMpt;
  },


// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
  'put_mpt' : function (village_coords, points){
	  window.setTimeout(function() {
		  var cacheMpt = get_mpt();
		  cacheMpt[village_coords] = points;
		  var to_save = serialize_x(cacheMpt);
		  TW_setValue("MPTrk", to_save);
	  },0);
  },

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
  'enhance_game_map': function(){
	  var TW_Image_Base = personals.getImageBase();
		// Get map size
	  var new_size = getValue("MSize");
	  var attackinfo = getValue("attacks")
	  if(!new_size) new_size = 15;

		// map controls
	  setFunc("resize_map", function(){
		  var mss = xpathGetFirst("//*[@id='map_size_select']");
		  var nsz = parseInt(mss.options[mss.selectedIndex].value);

		  window.setTimeout(function(){setValue("MSize", nsz);}, 0);
		  window.setTimeout("window.location.reload(true)", 100);
	  });

	  var form = $$("form")[1];
	  var sizes = [7, 10, 12, 15, 18, 20, 22, 24, 26, 28, 30];
	  var iHtml = '<table><tr><td colspan="2">&nbsp;</td></tr><tr><td align="right">Map size: </td><td><select id="map_size_select" onchange="resize_map()">';
	  for(kk=0; kk<sizes.length; kk++) iHtml += '<option ' + (sizes[kk]==new_size ? 'selected="selected" ' : '') + 'value="' + sizes[kk] +'">' + sizes[kk] + 'x' + sizes[kk] + (sizes[kk]==7?' (off)':'') + '</option>';

	  iHtml += '</select></td></tr>';
	  iHtml += '<tr><td align="right">Mark player: </td><td><input type="text" id="mark_player" size="8" /><input type="text" id="mark_tribe" size="8" /><a href="javascript:search_map();"><img src="'+TW_Image_Base+'/map/map_e.png" /></a></td></tr>';
	  iHtml += '</table>';
	  iHtml += '<table><tr><th>Display Attacks Current</th>';
	  iHtml += '<td><a href=\"javascript:search_map_attacks();\"><img src=\"'+TW_Image_Base+'/map/map_e.png\"></a></td></tr></table>';
	  form.innerHTML += iHtml;
		// end map controls

	  if(new_size == 7) return;

	  window.setTimeout(function() {
		  setValue("MSize", new_size);
	  },0);

 	setFunc("search_map_attacks", function(){
		var map = document.getElementById("mapCoords");
		var villages = map.getElementsByTagName("img");
		  for (i = 0; i < villages.length; i++) {
		  	var tmp = villages[i].getAttribute("onmouseover");
		  	if (tmp != null) {
		  	  	// attempt to find attacks and map
			  		var target = tmp.replace(/(.+)\((-?\d+\|-?\d+)\)\s(.+)/gi,"$2").split("|");
			  	   	for(var v in attackinfo) {
		 				var attack = attackinfo[v];
		 				var coords = attack.targetcoords.join('|');
		 				if(coords==target.join('|')) {
				 	 		//alert("Found one"+target.join('|')); 
				 	 		villages[i].setAttribute("src","graphic/unit_big/light.png");
				 	 		villages[i].style.width = '53px';
					  		villages[i].style.height = '38px';
		 				}
	 				}
	 		}
	 	}
	 });

	setFunc("search_map", function(){

		  var plr = xpathGetFirst("//*[@id='mark_player']");
		  var trb = xpathGetFirst("//*[@id='mark_tribe']");
		  var map = document.getElementById("mapCoords");

		  var villages = map.getElementsByTagName("img");

		  for (i = 0; i < villages.length; i++) {
			
			  var tmp = villages[i].getAttribute("onmouseover");

			  if (tmp != null) {
				  tmp = tmp.replace(/map_popup\('(.+)', '(.*)', '(.*)', (\d+), '(.+)\s\((.+)\)', '(.+)\s\((.+) Points\)', (\w+), (\w+), (\w+), (\w+)\)/gi, "$5 $7");

				  if (villages[i].getAttribute("rel") != null) {

					  villages[i].style.border = 'none';
					  villages[i].style.width = '53px';
					  villages[i].style.height = '38px';
					  villages[i].setAttribute("rel", null);
				  }

				  if (plr.value != '') {
					  if (tmp.match(new RegExp(plr.value, "i"))) {
						  villages[i].style.border = '1px solid red';
						  villages[i].style.width = '51px';
						  villages[i].style.height = '36px';
						  villages[i].setAttribute("rel","searched");
					  }
				  }
				  if (trb.value != '') {
					  if (tmp.match(new RegExp(trb.value+"$", "i")) && villages[i].getAttribute("rel") == null) {
						  villages[i].style.border = '1px solid blue';
						  villages[i].style.width = '51px';
						  villages[i].style.height = '36px';
						  villages[i].setAttribute("rel","searched");
					  }
				  }
			  }

		  }
	  });

	  var map_requests_needed = null;
	  var map_requests_size   = null;

	  if(new_size < 16){
		  map_requests_needed = 1;
	  }else{
		  map_requests_needed = 4;
		  map_requests_size   = parseInt(new_size / 2);
		  new_size = map_requests_size * 2;
	  }

		// Get mpt points
	  TW_Mpt = plugins.mapexpand.get_mpt();

		// Get current position
	  var map_x = getVar("mapX");
	  var map_y = getVar("mapY");
	  var map_s = getVar("mapSize");

		// Calculate new X and Y
	  var delta = parseInt((map_s - new_size) / 2);

		// Overwrite values
	  map_x += delta;
	  map_y += delta;

		// InnerHTML
	  var ihtml = "";
	  ihtml += '<tr>';
	  ihtml += '<td height="38">' + map_y + '</td>';
	  ihtml += '<td colspan="' + new_size + '" rowspan="' + new_size + '">';
	  ihtml += '<div style="background-image:url(graphic/map/gras1.png); position:relative; width:' + (53 * new_size) + 'px; height:' + (38 * new_size) +'px; overflow:hidden" id="map">';
	  ihtml += '<div id="mapOld" style="position:absolute">';
	  if(map_requests_needed == 4){
		  var w = 53 * map_requests_size + 1;
		  var h = 38 * map_requests_size + 2;
		  ihtml += '<table cellspacing="0" cellpadding="0"><tr><td><div id="old_1" style="width:' + w + 'px; height:' + h + 'px"><div style="margin:10px; color:white">' +  twe.lang("loading") + '</div></div></td><td><div id="old_2" style="width:' + w + 'px; height:' + h + 'px"><div style="margin:10px; color:white">&nbsp;</div></div></td></tr><tr><td><div id="old_3" style="width:' + w + 'px; height:' + h + 'px"><div style="margin:10px; color:white">&nbsp;</div></div></td><td><div id="old_4" style="width:' + w + 'px; height:' + h + 'px"><div style="margin:10px; color:white">&nbsp;</div></div></td></tr></table>';
	  }
	  ihtml += '<div style="margin:10px; color:white">' + twe.lang("loading") + '</div>';
	  ihtml += '</div>';
	  ihtml += '<div id="mapNew" style="position:absolute; left:0px; top:0px">&nbsp;</div>';
	  ihtml += '</div>';
	  ihtml += '</td>';
	  ihtml += '</tr>';
	  for(jj=1; jj<new_size; jj++){
		  ihtml += '<tr><td width="20" height="38">' + (map_y + jj) + '</td></tr>';
	  }
	  ihtml += '<tr id="map_x_axis">';
	  ihtml += '<td height="20"></td>';
	  for(jj=0; jj<new_size; jj++){
		  ihtml += '<td align="center" width="53">' + (map_x + jj) + '</td>';
	  }
	  ihtml += '</tr>';
	  xpathGetFirst("//*[@id='mapCoords']").innerHTML = ihtml;

		// Update data (asynchronously)
	  if(map_requests_needed == 1){
		  var url = twe.Server + "/" + getVar("mapURL") + '&start_x=' + map_x + '&start_y=' + map_y + '&size_x=' + new_size + '&size_y=' + new_size;
		  var xhReq = new XMLHttpRequest();
		  xhReq.open("GET", url, true);
		  xhReq.onreadystatechange = function(){
			  if(xhReq.readyState != 4 || xhReq.status != 200) return;
			  xpathGetFirst("//*[@id='mapOld']").innerHTML = xhReq.responseText;
		  }
		  xhReq.send(null);
	  }else{
		  var url_1 = twe.Server + "/" + getVar("mapURL") + '&start_x=' + map_x + '&start_y=' + map_y + '&size_x=' + map_requests_size + '&size_y=' + map_requests_size;
		  var url_2 = twe.Server + "/" + getVar("mapURL") + '&start_x=' + (map_x + map_requests_size) + '&start_y=' + map_y + '&size_x=' + map_requests_size + '&size_y=' + map_requests_size;
		  var url_3 = twe.Server + "/" + getVar("mapURL") + '&start_x=' + map_x + '&start_y=' + (map_y + map_requests_size) + '&size_x=' + map_requests_size + '&size_y=' + map_requests_size;
		  var url_4 = twe.Server + "/" + getVar("mapURL") + '&start_x=' + (map_x + map_requests_size) + '&start_y=' + (map_y + map_requests_size) + '&size_x=' + map_requests_size + '&size_y=' + map_requests_size;

		  var xhReq_1 = new XMLHttpRequest();
		  xhReq_1.open("GET", url_1, true);
		  xhReq_1.onreadystatechange = function(){
			  if(xhReq_1.readyState != 4 || xhReq_1.status != 200) return;
			  xpathGetFirst("//*[@id='old_1']").innerHTML = xhReq_1.responseText;
		  }
		  xhReq_1.send(null);

		  var xhReq_2 = new XMLHttpRequest();
		  xhReq_2.open("GET", url_2, true);
		  xhReq_2.onreadystatechange = function(){
			  if(xhReq_2.readyState != 4 || xhReq_2.status != 200) return;
			  xpathGetFirst("//*[@id='old_2']").innerHTML = xhReq_2.responseText;
		  }
		  xhReq_2.send(null);

		  var xhReq_3 = new XMLHttpRequest();
		  xhReq_3.open("GET", url_3, true);
		  xhReq_3.onreadystatechange = function(){
			  if(xhReq_3.readyState != 4 || xhReq_3.status != 200) return;
			  xpathGetFirst("//*[@id='old_3']").innerHTML = xhReq_3.responseText;
		  }
		  xhReq_3.send(null);

		  var xhReq_4 = new XMLHttpRequest();
		  xhReq_4.open("GET", url_4, true);
		  xhReq_4.onreadystatechange = function(){
			  if(xhReq_4.readyState != 4 || xhReq_4.status != 200) return;
			  xpathGetFirst("//*[@id='old_4']").innerHTML = xhReq_4.responseText;
		  }
		  xhReq_4.send(null);

		  setFunc("downloadMapData", function(x_mod, y_mod){

			  var map_x  = getVar("mapX");
			  var map_y  = getVar("mapY");
			  var map_s  = getVar("mapSize");
			  var map_ss = map_s / 2;

			  map_x += x_mod * map_s;
			  map_y += y_mod * map_s;

			  window.setTimeout(function() {
				  setVar("mapX", map_x);
				  setVar("mapY", map_y);}, 0);

				// Prepare new blocks
				  var w = 53 * map_ss + 1;
				  var h = 38 * map_ss + 1;
				  var map_new = getVar("mapNew");
				  map_new.innerHTML = '<table cellspacing="0" cellpadding="0"><tr><td><div id="new_1" style="width:' + w + 'px; height:' + h + 'px"><div style="margin:10px; color:white">' +  twe.lang("loading") + '</div></div></td><td><div id="new_2" style="width:' + w + 'px; height:' + h + 'px"><div style="margin:10px; color:white">&nbsp;</div></div></td></tr><tr><td><div id="new_3" style="width:' + w + 'px; height:' + h + 'px"><div style="margin:10px; color:white">&nbsp;</div></div></td><td><div id="new_4" style="width:' + w + 'px; height:' + h + 'px"><div style="margin:10px; color:white">&nbsp;</div></div></td></tr></table>';

				  var url_1 = twe.Server + "/" + getVar("mapURL") + '&start_x=' + map_x + '&start_y=' + map_y + '&size_x=' + map_ss + '&size_y=' + map_ss;
				  var url_2 = twe.Server + "/" + getVar("mapURL") + '&start_x=' + (map_x + map_ss) + '&start_y=' + map_y + '&size_x=' + map_ss + '&size_y=' + map_ss;
				  var url_3 = twe.Server + "/" + getVar("mapURL") + '&start_x=' + map_x + '&start_y=' + (map_y + map_ss) + '&size_x=' + map_ss + '&size_y=' + map_ss;
				  var url_4 = twe.Server + "/" + getVar("mapURL") + '&start_x=' + (map_x + map_ss) + '&start_y=' + (map_y + map_ss) + '&size_x=' + map_ss + '&size_y=' + map_ss;

				  var xhReq_1 = new XMLHttpRequest();
				  xhReq_1.open("GET", url_1, true);
				  xhReq_1.onreadystatechange = function(){
					  if(xhReq_1.readyState != 4 || xhReq_1.status != 200) return;
					  xpathGetFirst("//*[@id='new_1']").innerHTML = xhReq_1.responseText;
				  }
				  xhReq_1.send(null);

				  var xhReq_2 = new XMLHttpRequest();
				  xhReq_2.open("GET", url_2, true);
				  xhReq_2.onreadystatechange = function(){
					  if(xhReq_2.readyState != 4 || xhReq_2.status != 200) return;
					  xpathGetFirst("//*[@id='new_2']").innerHTML = xhReq_2.responseText;
				  }
				  xhReq_2.send(null);

				  var xhReq_3 = new XMLHttpRequest();
				  xhReq_3.open("GET", url_3, true);
				  xhReq_3.onreadystatechange = function(){
					  if(xhReq_3.readyState != 4 || xhReq_3.status != 200) return;
					  xpathGetFirst("//*[@id='new_3']").innerHTML = xhReq_3.responseText;
				  }
				  xhReq_3.send(null);

				  var xhReq_4 = new XMLHttpRequest();
				  xhReq_4.open("GET", url_4, true);
				  xhReq_4.onreadystatechange = function(){
					  if(xhReq_4.readyState != 4 || xhReq_4.status != 200) return;
					  xpathGetFirst("//*[@id='new_4']").innerHTML = xhReq_4.responseText;
				  }
				  xhReq_4.send(null);
		  });

			// ScrollX fix
		  function watchMouse(e){
			  var info = document.getElementById("info");
			  if(!info || info.style.visibility != "visible") return false;

			  var scrollX, scrollY, mouseX, mouseY;
			  if(e){
				  scrollX = window.pageXOffset;
				  scrollY = window.pageYOffset;
				  mouseX  = e.clientX;
				  mouseY  = e.clientY;
			  }else{
				  scrollX = document.body.scrollLeft;
				  scrollY = document.body.scrollTop;
				  mouseX  = window.event.clientX;
				  mouseY  = window.event.clientY;
			  }

			  info.style.left = mouseX + 5 + scrollX + "px";
			  info.style.top =  mouseY - 100 + scrollY + "px";
			  return true;
		  };

		  if(document.addEventListener) document.addEventListener("mousemove", watchMouse, true);
		  else document.onmousemove = watchMouse;
	  }

		// ajaxMapInit()
	  window.setTimeout(function() {
		  setVar("mapOld",  xpathGetFirst("//*[@id='mapOld']"));
		  setVar("mapNew",  xpathGetFirst("//*[@id='mapNew']"));
		  setVar("mapX",    map_x);
		  setVar("mapY",    map_y);
		  setVar("mapSize", new_size);
	  }, 0);

		// mapMoveTopo()
	  var scrollX = map_x;
	  var scrollY = map_y;
	  window.setTimeout(function() {
		  setVar("scrollX", scrollX);
		  setVar("scrollY", scrollY);
	  }, 0);
	  var topoX = parseInt(document.getElementsByName('min_x')[0].value);
	  var topoY = parseInt(document.getElementsByName('min_y')[0].value);

	  var relX = scrollX - topoX;
	  if(getVar("globalYDir") == 1){
		  var relY = scrollY - topoY;
	  }else{
		  var relY = (45-mapSize) - (scrollY-topoY);
	  }
	
		// Rechteck verschieben (whatever this mean :)
	  var topoRect = xpathGetFirst('//*[@id="topoRect"]');
	  topoRect.style.left   = (5*(relX)) + 'px';
	  topoRect.style.top    = (5*(relY)) + 'px';
	  topoRect.style.width  = (5*(new_size)) + 'px';
	  topoRect.style.height = (5*(new_size)) + 'px';

		// Tracking

	  setFunc("old_map_popup", getFunc("map_popup"));
	  setFunc("map_popup", function(title, bonus_image, bonus_text, points, owner, ally, village_groups, moral, village_id, source_id){
		  var x_title  = arguments[0];
		  var x_points = null;
		  if(arguments.length == 8){
			  x_points = arguments[1];
			  (getFunc("old_map_popup"))(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7]);
		  }else{
			  x_points = arguments[3];
			  (getFunc("old_map_popup"))(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7], arguments[8], arguments[9]);			
		  }

		
		  var tmp = x_title.match( /\(([^\)]+)/ );
		  var vlg_coords = tmp && tmp[1] ? tmp[1] : null;

		  if(vlg_coords != null){

			  vlg_coords = vlg_coords.replace(/\|/, "x");
	
				//var villagelinks = $("mapCoords").getElementsByTagName("a");
			  var villagelinks = xpathGetAll("//*[@id='mapCoords']//a");
			  for (i =0; i < villagelinks.length; i++) { 
			
				  var curvil = new String(villagelinks[i].innerHTML);
				  var curcord = curvil.replace(/(.+)\((-?\d+)\|(-?\d+)\)(.+)/gi, "$2x$3");
				  if (curcord == vlg_coords) {
					  curid = villagelinks[i].href.replace(/^(.+)id=(\d+)$/i, "$2");
				  }
			  }
			  var pointrackinfo = (plugins.mapexpand.get_mpt_xhtml(vlg_coords, x_points) != '') ? plugins.mapexpand.get_mpt_xhtml(vlg_coords, x_points) : plugins.mapexpand.get_mpt_xhtml(curid, x_points);
			  xpathGetFirst("//*[@id='info_points']").innerHTML = x_points + pointrackinfo;
		  }
	  });
  }
	};